package com.renting.modules.medical.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.renting.modules.medical.dao.MedicalImageDao;
import com.renting.modules.medical.entity.MedicalImage;
import com.renting.modules.renting.rentSys.entity.House;
import com.renting.modules.renting.rentSys.entity.HouseImage;
import main.java.com.UpYun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/5/10.
 */
@Service
public class MedicalImageService {

    @Autowired
    MedicalImageDao imageDao;
    @Autowired
    UpYun upYun;

    @Value("${up_bucket_url}")
    private String UP_BUCKET_URL;//服务器前缀

    public List<MedicalImage> medicalImages() {
        List<MedicalImage> list = new ArrayList<>();
        imageDao.findAll().forEach(medicalImage -> {
            list.add(medicalImage);
        });
        return list;
    }

    /**
     * 上传并保存医疗影像照片
     *
     * @param medicalImage
     */
    public void save(MedicalImage medicalImage, MultipartFile file) {

        try {
            String imgId = RandomUtil.simpleUUID();
            String mouthDir = DateUtil.format(new Date(), "yyyy-MM");
            String serverUrl = "/medical/" + mouthDir + "/" + imgId + ".jpg";
            boolean isUpload = upYun.writeFile(serverUrl, file.getBytes(), true);
            if (isUpload) {//图片上传成功
                medicalImage.setId(imgId);
                medicalImage.setServerUrl(serverUrl);
                medicalImage.setVisitUrl(UP_BUCKET_URL + "/" + serverUrl);//网络路径
                medicalImage.setCreateTime(DateUtil.date());
                imageDao.save(medicalImage);
            }
            imageDao.save(medicalImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除医疗影像照片
     *
     * @param medicalImage
     */
    public void delete(MedicalImage medicalImage) {
        imageDao.deleteById(medicalImage.getId());
    }


}
